package com.codeying.controller;

import com.codeying.component.excel.ExcelLogs;
import com.codeying.component.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codeying.utils.component.*;
import com.codeying.utils.*;
import com.codeying.entity.*;
import com.codeying.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.io.InputStream;
import java.util.*;
import java.io.File;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;
import jakarta.servlet.ServletOutputStream;
/** 我的题库功能 关于我的题库增删改查等 */
@Controller
@RequestMapping({"questionBank"})
public class QuestionBankController extends BaseController {

  /**
   * 我的题库列表页
   *
   * @param model
   * @param pageIndex
   * @param orderby
   * @return
   */
  @RequestMapping("list")
  public String list(Model model, Integer pageIndex, String[] orderby) {
    if (pageIndex == null) {
      pageIndex = 1; // 默认访问我的题库第一页,分页
    }

    IPage<QuestionBank> pageInfo =
        new Page<QuestionBank>().setCurrent(pageIndex).setSize(15); // 分页大小
    // 获取我的题库列表数据
    QueryWrapper<QuestionBank> queryWrapper = getQueryWrapper(orderby);
    // User  只能看关联了自己的
    if (req.getSession().getAttribute("role") != null
        && req.getSession().getAttribute("role").equals("user")) {
      queryWrapper.eq(
          "userid", ((User) req.getSession().getAttribute("user")).getId()); // 只能查看和自己相关的内容
    }

    // 使用原始我的题库queryWrapper进行分页查询（未被修改select条件）
    pageInfo = questionBankService.page(pageInfo, queryWrapper);
    // 获取到的我的题库
    List<QuestionBank> questionBankList = pageInfo.getRecords();

    // 将数据放入request
    List<User> useridFrnList = userService.list(new QueryWrapper<User>());
    model.addAttribute("useridFrnList", useridFrnList);

    // 循环遍历list数据，统计、获取外键数据
    for (QuestionBank e : questionBankList) {
      // 获取外键数据:用户
      e.setUseridFrn(userService.getById(e.getUserid()));
    }
    model.addAttribute("questionBankList", questionBankList);
    // 将分页信息传回前端
    PagerVO pager =
        new PagerVO(
            (int) pageInfo.getCurrent(), (int) pageInfo.getSize(), (int) pageInfo.getTotal());
    model.addAttribute("pager", pager);
    return "/pages/questionBank-list";
  }

  /**
   * 获取查询条件
   *
   * @param orderby
   * @return
   */
  private QueryWrapper<QuestionBank> getQueryWrapper(String[] orderby) {
    // 用于存储查询的条件
    QueryWrapper<QuestionBank> paramMap = new QueryWrapper<>();
    String userid = req.getParameter("userid");
    if (!StringUtils.isEmpty(userid)) {
      paramMap.eq("userid", userid);
      req.setAttribute("userid", userid);
    }
    String name = req.getParameter("name");
    if (!StringUtils.isEmpty(name)) {
      paramMap.like("name", name);
      req.setAttribute("name", name);
    }
    String labels = req.getParameter("labels");
    if (!StringUtils.isEmpty(labels)) {
      paramMap.like("labels", labels);
      req.setAttribute("labels", labels);
    }
    String createtimeL = req.getParameter("createtimeL");
    String createtimeR = req.getParameter("createtimeR");
    if (!StringUtils.isEmpty(createtimeL)) {
      paramMap.ge("createtime", DateUtil.strToDate(createtimeL));
      req.setAttribute("createtimeL", createtimeL);
    }
    if (!StringUtils.isEmpty(createtimeR)) {
      paramMap.le("createtime", DateUtil.strToDate(createtimeR));
      req.setAttribute("createtimeR", createtimeR);
    }

    String orderByStr = "id desc"; // 默认根据id降序排序
    if (orderby != null && orderby.length > 0) { // 如果前端传来了需要排序的字段，那么根据前端字段排序
      // 前端回显
      for (String s : orderby) {
        req.setAttribute(s.replace(" ", ""), true);
      }
      orderByStr = Arrays.toString(orderby);
      // 前端传来的排序字段都会有","开头，去掉第一个逗号
      orderByStr = orderByStr.substring(1, orderByStr.length() - 1);
    }
    // 默认按照id排序
    paramMap.last("order by " + orderByStr);
    return paramMap;
  }

  // 前往我的题库编辑页
  @RequestMapping("edit")
  public String edit(String id, Model model) {
    // 根据id获取
    QuestionBank entity = questionBankService.getById(id);
    // 获取外键数据，填充到下拉框 :用户
    List<User> useridFrnList = userService.list(new QueryWrapper<User>());
    model.addAttribute("useridFrnList", useridFrnList);
    if (entity == null) {
      entity = new QuestionBank();
      entity.setUserid(req.getParameter("userid"));
      model.addAttribute("item", entity);
      return "/pages/questionBank-add";
    } else {
      model.addAttribute("item", entity);
      return "/pages/questionBank-edit";
    }
  }

  // 我的题库详情页
  @RequestMapping("detail")
  public String detail(@RequestParam("id") String id, Model model) {
    QuestionBank entity = questionBankService.getById(id);
    // 获取外键数据：用户
    entity.setUseridFrn(userService.getById(entity.getUserid()));
    model.addAttribute("item", entity);
    return "/pages/questionBank-detail";
  }

  // 我的题库保存
  @RequestMapping("save")
  @ResponseBody
  public ApiResult save(QuestionBank entityTemp) {
    String id = entityTemp.getId(); // 我的题库主键
    String userid = entityTemp.getUserid(); // 用户
    String name = entityTemp.getName(); // 题目名
    String content = entityTemp.getContent(); // 题目内容
    String answer = entityTemp.getAnswer(); // 题目答案
    String labels = entityTemp.getLabels(); // 知识点
    Date createtime = entityTemp.getCreatetime(); // 创建时间

    // 新增或更新
    if (entityTemp.getId() == null || "".equals(entityTemp.getId())) { // 新增
      id = CommonUtils.newId();
      entityTemp.setId(id);
      createtime = new Date();
      entityTemp.setCreatetime(createtime);
      // before add

      questionBankService.save(entityTemp);
    } else {
      // before edit

      questionBankService.updateById(entityTemp);
    }
    return ApiResult.successMsg("操作成功"); // 返回成功
  }

  // 我的题库删除
  @RequestMapping("delete")
  @ResponseBody
  public ApiResult delete(String id) {
    QuestionBank delTemp = questionBankService.getById(id);
    // before del

    // 根据ID删除记录
    questionBankService.removeById(id);
    return success();
  }

  // 从excel导入数据
  @PostMapping("excel")
  @ResponseBody
  public ApiResult importexcel(@RequestParam(value = "excel") MultipartFile excel)
      throws IOException {
    if (excel != null) {
      try {
        InputStream inputStream = excel.getInputStream();
        Collection<Map> importExcel =
            ExcelUtil.importExcel(
                Map.class, inputStream, "yyyy年MM月dd日 HH:mm:ss", new ExcelLogs(), 0);
        List<QuestionBank> list = new ArrayList<>();
        for (Map m : importExcel) {
          QuestionBank entity = new QuestionBank();
          entity.setId(CommonUtils.newId());
          User userid = userService.getBy("username", (String) m.get("用户"));
          if (userid != null) {
            entity.setUserid(userid.getId());
          }
          entity.setName((String) m.get("题目名"));
          entity.setContent((String) m.get("题目内容"));
          entity.setAnswer((String) m.get("题目答案"));
          entity.setLabels((String) m.get("知识点"));
          entity.setCreatetime(DateUtil.strToDate((String) m.get("创建时间"))); // 时间
          list.add(entity);
        }
        questionBankService.saveBatch(list);
        return ApiResult.successMsg("导入成功");
      } catch (Exception e) {
        e.printStackTrace();
        return ApiResult.fail("文件解析失败,请检查内容是否正确！");
      }
    } else {
      return (ApiResult.fail("请选择文件"));
    }
  }

  // 导出excel
  @RequestMapping("excel")
  public void excel() throws IOException {
    // 获取数据
    List<QuestionBank> data = questionBankService.list(getQueryWrapper(null));
    // 循环遍历list数据，统计、获取外键数据
    for (QuestionBank stAv : data) {
      // 获取外键数据:用户
      stAv.setUseridFrn(userService.getById(stAv.getUserid()));
      if (stAv.getUseridFrn() != null) {
        stAv.setUserid(stAv.getUseridFrn().getUsername());
      }
    }
    HashMap<String, String> headMap = new LinkedHashMap<>();
    headMap.put("userid", "用户");
    headMap.put("name", "题目名");
    headMap.put("content", "题目内容");
    headMap.put("answer", "题目答案");
    headMap.put("labels", "知识点");
    headMap.put("createtime", "创建时间");
    Collection<Object> dataset = new ArrayList<>(data);
    resp.setHeader("Content-Disposition", "attachment; filename=" + "questionBank.xls");
    resp.setDateHeader("expries", -1);
    resp.setHeader("Cache-Control", "no-cache");
    resp.setHeader("Pragma", "no-cache");
    ServletOutputStream servletOutputStream = null;
    try {
      servletOutputStream = resp.getOutputStream();
      ExcelUtil.exportExcel(headMap, dataset, servletOutputStream);
      servletOutputStream.close();
    } catch (IOException e) {
      System.out.println("IOException");
    }
  }
}

